package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2021/11/20 14:08
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public void transfer(int fromId, int destId, int money) {
        int fromMoney = accountMapper.selectMoneyById(fromId);
        int destMoney = accountMapper.selectMoneyById(destId);

        fromMoney -= money;
        destMoney += money;

        int finalFromMoney = fromMoney;
        int finalDestMoney = destMoney;
        /*transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                accountMapper.update(fromId, finalFromMoney);
                int i = 1 / 0;
                accountMapper.update(destId, finalDestMoney);
                return null;//这个返回值会给到TransactionTemplate的execute方法
            }
        });*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                accountMapper.update(fromId, finalFromMoney);
                int i = 1 / 0;
                accountMapper.update(destId, finalDestMoney);
            }
        });
    }
}
